import json
import pygal
import pygal_maps_world.maps
from pygal_maps_world.i18n import COUNTRIES

file_name = 'chapter_16_population_data.json'


def get_country_code(country_name):
    """根据指定的国家,返回Pygal使用的两个字母的国别码"""
    for code, name in COUNTRIES.items():
        if name == country_name:
            return code
        else:
            return None


with open(file_name) as f:
    pop_data = json.load(f)

    # 打印每个国家 2010 年的人口数量
    for pop_dict in pop_data:
        if pop_dict['Year'] == '2010':
            country_code = pop_dict['Country Code']
            country_name = pop_dict['Country Name']
            population = int(float(pop_dict['Value']))
            print(country_name + ": " + str(population))

            # code = get_country_code(country_name)
            # if code:
            #     print(code + ": " + str(population))
            # else:
            #     print('ERROR - ' + country_name)

# 绘制图表
wm = pygal_maps_world.maps.World()
# wm.title = 'North, Central, and South America'
# wm.add('North America', ['ca', 'mx', 'us'])
# wm.add('Central America', ['bz', 'cr', 'gt', 'hn', 'ni', 'pa', 'sv'])
# wm.add('South America', ['ar', 'bo', 'br', 'cl', 'co', 'ec', 'gf','gy', 'pe', 'py', 'sr', 'uy', 've'])
# wm.render_to_file('americas.svg')

wm = pygal_maps_world.maps.World()
wm.title = 'Populations of Countries in North America'
wm.add('North America', {'ca': 34126000, 'us': 309349000, 'mx': 113423000})
wm.render_to_file('na_populations.svg')